<?php 
namespace app\home\controller;
use think\Controller;
use think\Db;	
use think\Session;
use think\request;

//操盘管理
class Tradermng extends Base{
	public function index(){
		$user = $this->userInformation();
		if($user['RNA']!=1) return  "<script>alert('实名认证通过才能进行该操作');window.location.href='".url('certification/index')."'</script>";
		if($user['assetaccount']==null) return  "<script>alert('请先开户');window.location.href='".url('certification/index')."'</script>";
		if($user['assetaccount']=='00000') return  "<script>alert('开户申请中请');window.location.href='".url('certification/index')."'</script>";
		//$userAllocation = Db::name('user_allocation')
		//			->where(['uid'=>$user['id']])
		//			->order('id desc')
//                    ->select();
		//			->paginate(10);
//					 dump($userAllocation);
//die;
$userAllocation = Db::name('allocationpriority')->where('uid',$user['id'])->order('id','desc')->paginate(10);
		$page = $userAllocation->render();
		$this->assign('page',$page);
		$this->assign('userAllocation',$userAllocation);
		return $this->fetch('Tradermng/index',['userAllocation'=>$userAllocation]);
	}

	/**
	 * @param $userAllocation['transactionamount'] 总金额
	 * @param $userAllocation['allocation'] 优先资金或者配资的资金
	 * @param $userAllocation['bond'] 配资表用户自己的钱
	 * @param $user['assetaccount'] 用户的期货账户
	 * @param $user['balance'] 用户的余额
	**/



	//结束操盘
	public function endThedisk(){
//        dump($this->jitou());die;
		$time = Db::name('config')->where('key','jstime')->find()['value'];
		$s = explode('-',$time);
		if(date('H:i') >= $s[0] && date('H:i') <= $s[1]) return json_encode(['msg'=>"$s[0]~$s[1]时为结算时间，不允许出入金"],JSON_UNESCAPED_UNICODE);
		if(Session::get('codes')!=$_POST['codes']) return json_encode(['msg'=>'系统正在处理中求请勿重复提交!'],JSON_UNESCAPED_UNICODE);
		Session::set('codes',mt_rand(1000,9999));		
		
		$user = $this->userInformation();
		$userAllocation = Db::name('user_allocation')->where(['uid'=>$user['id'],'status'=>'1'])->find();
		$qjgj = Db::name('futures_api')->where(['id'=>$user['fwq']])->find();
		if($qjgj['title']=='jt'){
			$data = $this->jitou();
		}else{
		$data = $this->userQuery();
		}
		if($data['Margin']==0){

			$requestid=6;                    //用户结果与请求统一的值
			$account=$user['assetaccount'];  //用户户账号
			$amount='-'.$userAllocation['allocation']; //出金金额
			$credit='-'.$userAllocation['allocation']; //$data['Credit'];//优先资金
			$remark=iconv("UTF-8", "GBK", '取消操盘');
//    		$qjgj = Db::name('futures_api')->where(['state'=>1])->find();/**/
            $qjgj = Db::name('futures_api')->where(['id'=>$user['fwq']])->find();

            //var_dump($qjgj);die;
            if($qjgj['title']=='jt'){
                //出金优先资金
                $HighBalance = $this->jitou()['HighBalance'];
                //var_dump($credit);die;
        	    //金额是以分为单位
           	    $req['Action']='ReqTransfer';
                $req['ChdAccountID']=$account;
//                $req['PriorityAmount']=$credit*100;
                $req['PriorityAmount']='-'.$HighBalance;
                $req['BadAmount']=0;
                //var_dump($payCj);
                $req['UserID']=$qjgj['sa'];
                ksort($req);
                $url='';
                foreach ($req as $k=>$v){
                    $url=$url.$k.'='.$v.'&';
                }
                $req=rtrim($url,'&');
                //var_dump($req);
                $sign=md5($req.'&UserKey='.$qjgj['sapass']);
                $req=$req.'&Sign='.$sign;
                //var_dump($req);
                $url=$qjgj['api'].'?'.$req;
                //var_dump($url);
                $res=https_request($url);
               // var_dump($res);
                $ar=json_decode($res,true);
               //var_dump($ar);die;
                if($ar['ErrorID']==0){
                    $ar['Error']['Code']=0;
                     //return $ar;
                }else{
                    $ar['Error']['Code']=1;
                	$ar['Error']['Message']=$ar['ErrorMsg'];
                }
            }else{
			// $url="https://moni.byxgj.com:13134/deposit?requestid=$requestid&sa=$sa&sapass=$sapass&account=$account&amount=$amount&credit=$credit&remark=$remark";
//			$url="{$qjgj['api']}deposit?requestid=$requestid&sa={$qjgj['sa']}&sapass={$qjgj['sapass']}&account=$account&amount=$amount&credit=$credit&remark=$remark";
//
//			$curl = curl_init(); //启动一个CURL会话
//			curl_setopt($curl, CURLOPT_URL, $url);
//			curl_setopt($curl, CURLOPT_HEADER, 0);
//			curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
//			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
//			$tmpInfo = curl_exec($curl);     //返回api的json对象
//			//关闭URL请求
//			curl_close($curl);
//			$arr = simplexml_load_string($tmpInfo);
//			$xmljson= json_encode($arr );//将对象转换个JSON
//			$xmlarray=json_decode($xmljson,true);//将json转换成数组
//			$ar=$xmlarray['Result'];
//            if(!isset($ar)){
//                return "<script>alert('期货账户有问题，请联系客户！');window.location.href='".url('home/Deposit/deposit')."'</script>";
//            }
            }
			// //var_dump($ar);
			// //出入金记录
			// //var_dump($ar);exit;
			// return json_encode(['msg'=>$ar],JSON_UNESCAPED_UNICODE);
			// //是否出金成功 0是入金成功
			if($ar['Error']['Code']==0){
				Db::startTrans();
			    try{					
					//期货配资资金记录
					$allocation = [
						'uid' => $user['id'],
						'futuresID'=>$account,
						'priorityfunds'=>'-'.$HighBalance/100,
						'eae'=>0,//出金
						'state'=>$ar['Error']['Code'],//成功或者失败	
					];
					Db::name('allocationpriority')->insert($allocation);
					$y = $userAllocation['allocation']/10000;
					$x= $HighBalance/1000000;
					$ups = [
						'status' => 0,
						'endtime' => date('Y-m-d H:i:s'),
                        'allocation'=>'原:'.$y.'万元/现:'.$x.'万元',
					];
					// Db::name('user_futures')->insert($list);
					$arr=Db::name('user_allocation')->where(['uid'=>$user['id'],'status'=>1])->update($ups);
					// $users = Db::name('users')->where(['id'=>$user['id']])->update(['updatetime'=>date('Y-m-d H:i:s')]);
					Db::commit();
		        } catch (\Exception $e) {
		            //回滚事务
		            Db::rollback();
		            return json_encode(['msg'=>'执行失败'],JSON_UNESCAPED_UNICODE);
		        }

		        	return json_encode(['msg'=>'success']);

			}else{
				return json_encode(['msg'=>'操作失败'],JSON_UNESCAPED_UNICODE);
			}	
			// }			
		}else{
			return json_encode(['msg'=>'请先取消保证金'],JSON_UNESCAPED_UNICODE);
		}
	}

	/**
	 * @param $userAllocation['transactionamount'] 总金额
	 * @param $userAllocation['allocation'] 优先资金或者配资的资金
	 * @param $userAllocation['bond'] 配资表用户自己的钱
	 * @param $user['assetaccount'] 用户的期货账户
	 * @param $user['balance'] 用户的余额
	**/

	// 开始操盘
	// public function Startthedisk(){
	// 	if(date('H:i') >= '16:00'){
	// 		return json_encode(['msg'=>'结算已完成，不允许出入金'],JSON_UNESCAPED_UNICODE);
	// 	}
	// 	$user = $this->userInformation();
	// 	$userAllocation = Db::name('user_allocation')
	// 	->where(['uid'=>$user['id'],'status'=>0])
	// 	// ->where('status','not in','2')
	// 	->find();

	// 	if($user['balance']/$userAllocation['allocation'] < 1/10){
	// 		return json_encode(['msg'=>'操盘配资余额不足请充值'],JSON_UNESCAPED_UNICODE);
	// 	}
	// 	$m = $user['balance'] - $userAllocation['bond'];

	// 	if($m<0){
	// 		return json_encode(['msg'=>'余额不足'],JSON_UNESCAPED_UNICODE);
	// 	}
	// 		Db::startTrans();
	// 	    try{		

	// 			$up = Db::name('users')
	// 				->where(['id'=>$user['id']])
	// 				->update(['updatetime'=>date('Y-m-d H:i:s'),'balance'=>$m]);

	// 		Db::commit();
	//     } catch (\Exception $e) {
	//             //回滚事务
	//         Db::rollback();
	//             return json_encode(['msg'=>'执行失败'],JSON_UNESCAPED_UNICODE);
	//      }		
 //    	$requestid=6;                    //用户结果与请求统一的值
 //    	$account=$user['assetaccount'];  //用户户账号
 //    	$sa='qjgj';                      //期货管理员账号
	//     $sapass='123';                   //期货管理员密码
 //    	$amount=$userAllocation['transactionamount'];//入金金额
 //    	$credit=$userAllocation['allocation'];//优先资金
 //    	$remark=iconv("UTF-8", "GBK", '账户转期货');
 //    	$remark=$remark;
 //    	$url="https://moni.byxgj.com:13134/deposit?requestid=$requestid&sa=$sa&sapass=$sapass&account=$account&amount=$amount&credit=$credit&remark=$remark";
 //    	// echo $url;die;
 //    	$curl = curl_init(); // 启动一个CURL会话
	//     curl_setopt($curl, CURLOPT_URL, $url);
	//     curl_setopt($curl, CURLOPT_HEADER, 0);
	//     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	//     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
	//     curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
	//     $tmpInfo = curl_exec($curl);     //返回api的json对象
	//      //关闭URL请求
	//     curl_close($curl);
	//     $arr = simplexml_load_string($tmpInfo);
	//     $xmljson= json_encode($arr );//将对象转换个JSON  
	//     $xmlarray=json_decode($xmljson,true);//将json转换成数组  
	//     $ar=$xmlarray['Result'];		

	// 	$list['uid']=$user['id'];
	//     $list['futuresID']=$account;
	//     $list['eae']=1;
	//     $list['amount']='-'.$userAllocation['bond'];
	//     $list['del']=$ar['Error']['Code'];
	//     $list['remakes']='账户转期货';

	// 	if($ar['Error']['Code']==0){
 //     		//入金成功扣除余额
	// 		// $price=$user['balance']-$amount;
	// 		//资金日志
	// 		$dat['uid']	=$user['id'];
	// 		$dat['type']=5;
	// 		$dat['price']='-'.$userAllocation['bond'];
	// 		$dat['balance']=$m;

	// 		//期货金记录
	// 		$allocation = [
	// 			'uid' => $user['id'],
	// 			'futuresID'=>$account,
	// 			'priorityfunds'=>$userAllocation['allocation'] ,
	// 			'eae' => 1,
	// 			'state'=>$ar['Error']['Code']
	// 		];
	// 		Db::name('allocationpriority')->insert($allocation);
	// 		Db::startTrans();
	// 	    try{				
	// 			Db::name('user_futures')->insert($list);
	// 			Db::name('cashlog')->insert($dat);
	// 			Db::name('user_allocation')->where(['uid'=>$user['id']])->where('status','not in','2')->update(['status'=>1]);
	// 		Db::commit();
				
	// 	    } catch (\Exception $e) {
	// 	            //回滚事务
	// 	        Db::rollback();
	// 	            return json_encode(['msg'=>'执行失败'],JSON_UNESCAPED_UNICODE);
	// 	    }

	// 	    return json_encode(['msg'=>'success']);
 //      	}else{
 //     		return  json_encode(['msg'=>'操作失败'],JSON_UNESCAPED_UNICODE);
 //       	}

	// }


	public function  userQuery(){
		//此账号是否开户
		// $ste=Db::name('users')->where('id',Session::get('uid'))->field('assetaccount,balance')->find();
		$user = $this->userInformation();
		header("Content-type: text/html; charset=utf-8");
		$requestid=6;
        $qjgj = Db::name('futures_api')->where(['state'=>1])->find();
        if($qjgj['title']=='jt'){
        	//吉投
        	
        }else{
        	//期金管家
		$account=$user['assetaccount'];                               //用户账号
	    $url="{$qjgj['api']}queryaccount?requestid=$requestid&sa={$qjgj['sa']}&sapass={$qjgj['sapass']}&account=$account";
	    //echo $url;
		$curl = curl_init(); // 启动一个CURL会话
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
		$tmpInfo = curl_exec($curl);     //返回api的json对象
		//关闭URL请求
		curl_close($curl);
		$arr = simplexml_load_string($tmpInfo);
		$xmljson= json_encode($arr );//将对象转换个JSON  
		$xmlarray=json_decode($xmljson,true);//将json转换成数组  
		$ar=$xmlarray['Result'];
		$data=array();
		$data=$ar['Summary'];
	    // var_dump($data);
	     //劣后资金
	    $data['bad']=$data['Balance']-$data['Credit'];
	      //var_dump($data['bad']);
        return  $data;
           // dump($data);
	     }
	     }
	     
//吉投
 public function jitou(){
    	 //此账号是否开户
        $ste = Db::name('users')->where('id=' . Session::get('uid'))->field('assetaccount,balance,fwq')->find();
        //var_dump($ste);
        if ($ste['assetaccount'] !== '' and $ste['assetaccount'] != '00000') {
        	 $qjgjz = Db::name('futures_api')->where(['id'=>$ste['fwq']])->find();
        	 $req['Action']='ReqQryAccountInfo';
                $req['ChdAccountID']=$ste['assetaccount'];
                $req['UserID']=$qjgjz['sa'];
                ksort($req);
                $url='';
                foreach ($req as $k=>$v){
                    $url=$url.$k.'='.$v.'&';
                }
                $req=rtrim($url,'&');
                //var_dump($req);
                $sign=md5($req.'&UserKey='.$qjgjz['sapass']);
                $req=$req.'&Sign='.$sign;
               //var_dump($req);
                $url=$qjgjz['api'].'?'.$req;
               // var_dump($url);
                $res=https_request($url);
                //var_dump($res);
                //var_dump(json_decode($res,true));
                $data=json_decode($res,true);
                if($data['ErrorID']==0){
                $data['bad']=$data['LowAvailable']/100;
                $data['Margin']=$data['CurrMargin']/100;
                $data['Available']=$data['Available']/100;
                if ($data['CurrMargin'] == 0 and $data['FrozenMargin'] == 0){
                	$data['Margin']=0;
                }
        	    return $data;
        	    }else{
        	    	//没有查到此账号
        	    	$data=1;
        	   return $data;
        	    }
        }
    	
    }
}